package com.ndp.fb.mq.service.schedulerservice.adpublish;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ndp.fb.enums.publish.OptimizationGoal;
import com.ndp.fb.fbagent.service.TargetingSpecFBService;
import com.ndp.fb.model.fbagent.param.APIPriority;
import com.ndp.fb.model.fbagent.param.ApiCallBackTarget;
import com.ndp.fb.model.fbagent.param.useraudience.TargetingSpecParam;
import com.ndp.fb.mq.api.service.schedulerservice.AdAccountsSchedulerService;
import com.ndp.fb.mq.service.schedulerservice.thirdpictureaudit.AutoCheckConstant;
import com.ndp.fb.rdb.api.GeolocationRdbService;
import com.ndp.fb.rdb.model.AdGeolocation;
import com.ndp.fb.util.StringUtil;
import com.restfb.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by infi.he on 2016/1/4.
 */
@Component
public class FetchFbUsersService {


    private static Logger logger = LoggerFactory.getLogger(FetchFbUsersService.class);

    @Reference
    GeolocationRdbService geolocationRdbService;

    @Autowired
    private AdAccountsSchedulerService adaccountsSchedulerService;

    @Reference
    private TargetingSpecFBService targetingSpecFBService;

    //
    public void fetchFbUsers() {
        logger.info("FetchFbUsersService fetchFbUsers 开始 ");

        Long accountId = AutoCheckConstant.getFbAccountId();
        String accessToken = adaccountsSchedulerService.getAdaccountsToken(accountId);
        if (StringUtil.isEmpty(accessToken))
            return;

        List<AdGeolocation> all = geolocationRdbService.getAll();
        for (AdGeolocation adGeolocation : all) {

            String targetingSpec = "{\"age_max\":65,\"age_min\":13,\"geo_locations\":{\"countries\":[\"" + adGeolocation.getCountryCode() + "\"]}}";
            logger.info("FetchFbUsersService fetchFbUsersCallback>>> CountryCode >>> " + adGeolocation.getCountryCode() + " 回调完成 ");

            TargetingSpecParam targetingSpecReachEstimateParam = new TargetingSpecParam();
            targetingSpecReachEstimateParam.setTargetingSpec(targetingSpec);
            targetingSpecReachEstimateParam.setCallBack(true);
            targetingSpecReachEstimateParam.setFbAccountId(accountId);
            targetingSpecReachEstimateParam.setAccessToken(accessToken);
            targetingSpecReachEstimateParam.setApiCallbackTargetType(ApiCallBackTarget.AdPublish.TargetingSpecUsers.getTargetType());
            targetingSpecReachEstimateParam.setApiPriorityCode(APIPriority.UserAudienceReach.getCode());
            targetingSpecReachEstimateParam.setOptimizeFor(OptimizationGoal.NONE.getCode());
            Map<String, String> equipment = new HashMap<>();
            equipment.put("id", adGeolocation.getId() + "");
            equipment.put("CountryCode", adGeolocation.getCountryCode());
            targetingSpecReachEstimateParam.setEquipment(equipment);
            targetingSpecFBService.targetingSpecReachEstimate(targetingSpecReachEstimateParam);
        }
    }

    public void fetchFbUsersCallback(Map<String, String> equipment, String response) {
        String id = equipment.get("id");
        String CountryCode = equipment.get("CountryCode");
        try {
            JsonObject jsonObject = new JsonObject(response).getJsonObject("data");
            Long people = jsonObject.getLong("users");
            geolocationRdbService.updateFbUsers(Long.valueOf(id), people);
        } catch (Exception e) {
            logger.error("FetchFbUsersService fetchFbUsersCallback >>> CountryCode >>> " + CountryCode + " 失败", e);
        } finally {
            logger.info("FetchFbUsersService fetchFbUsersCallback>>> CountryCode >>> " + CountryCode + " 回调完成 ");
        }
    }
}
